<?php 
/**
 * 请求管理类
 * 
 * Copyright (c) 2014~2019 https://desion.net All rights reserved.
 * Author: 阿林 QQ:120867629 <linhong00@gmail.com>
 */
declare (strict_types = 1);
namespace dsphp\http;

trait Response
{
    // 发送头部信息
    protected $headers = [];
    // 发送状态码
    protected $code = 200;

    // 初始化
    private function _initResponse()
    {
        $this->setContentType();
    }

    /**
     * 发送HTTP状态
     *
     * @param  integer $code 状态码
     * @return $this
     */
    public function code(int $code = 200)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * 获取
     */
    public function getHeader():array
    {
        return $this->headers;
    }

    /**
     * 设置响应头
     *
     * @param  string|array $name  参数名
     * @param  string       $value 参数值
     * @return $this
     */
    public function setHeader($name, $value = null)
    {
        if (is_array($name)) {
            $this->headers = array_merge($this->headers, $name);
        } else {
            $this->headers[$name] = $value;
        }

        return $this;
    }

    /**
     * 页面输出类型
     *
     * @param  string $contentType 输出类型
     * @param  string $charset     输出编码
     * @return $this
     */
    public function setContentType(string $contentType = 'text/html', string $charset = 'utf-8')
    {
        $this->setHeader('Content-Type', $contentType . '; charset=' . $charset);
        return $this;
    }
    // JSON类型
    public function setContentTypeJson(string $charset = 'utf-8')
    {
        return $this->setContentType('application/json', $charset);
    }

    /**
     * 设置页面不做任何缓存
     *
     * @return $this
     */
    public function noCache()
    {
        $this->headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0';
        $this->headers['Pragma']        = 'no-cache';

        return $this;
    }

    /**
     * Expires
     *
     * @param  string $time
     * @return $this
     */
    public function expires($time)
    {
        $this->headers['Expires'] = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + $time) . ' GMT';

        return $this;
    }
}